<template>
  <div>
    <el-button type="primary" @click="dialogFormVisible = true">新增</el-button>
    <el-table
        :data="tableData"
        style="width: 100%">
      <el-table-column
          label="id"
          width="180">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column
          label="姓名"
          width="180">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>姓名: {{ scope.row.userName }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.userName }}</el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row)">编辑
          </el-button>
          <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="新增" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="姓名" :label-width="formLabelWidth">
          <el-input v-model="form.userName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'App',
  data() {
    return {
      tableData: [],
      dialogFormVisible: false,
      form: {
        userName: '',
      },
      formLabelWidth: '120px'
    }
  },
  methods: {
    selectAll() {
      axios.get('http://localhost:9000/user').then((res) => {
        this.tableData = res.data;
      })
    },
    save() {
      axios.post('http://localhost:9000/user/save', this.form).then(() => {
        this.selectAll();
        this.dialogFormVisible = false;
      })
    },
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogFormVisible = true;
      this.form = JSON.parse(JSON.stringify(row));
    },
    handleDelete(index, row) {
      console.log(index, row);
      axios.delete(`http://localhost:9000/user/delete/${row.id}`).then(() => {
        this.selectAll();
      })
    },
  },
  mounted() {
    this.selectAll();
  }
}
</script>
